import axios from 'axios';
import Vue from 'vue';

// import Cookies from 'js-cookie'
import Common from './common.js';
// import { Toast } from 'vant'
import router from '@/router';
// import qs from 'qs'
// import merge from 'lodash/merge'
import { clearLoginInfo } from '@/utils';
import { message, Loading } from 'element-ui';
// let questionList = [
//         '/operation/course/listQuestion',
//         '/operation/netSchool/homework/listQuestionsByVolumeId',
//         '/operation/course/associateVolumeWithCourse',
//         '/operation/referenceLib/search'
//     ]
// const token = Cookies.get('userToken')
function handleErrorCode(error, config) {
  // return;
  switch (error.code) {
    /** TODO: 补全错误码处理 */
    /* 登录失效或未登录 */
    case 401:
      clearLoginInfo();
      router.push({ name: 'login' });
      break;
    case 3333:
      console.log('fetch统一处理错误：：：：', error.info);
      /** 清除用户                                                                                                                                                                                                              */
      break;
    default:
    // config.hasRetErrorTip && Common.warn(error.info || error.message);
  }
}
// 处理搜索中condition字段
function parseFilter(filter) {
  return Object.keys(filter)
    .filter((key) => filter[key] && filter[key] !== '')
    .map((key) => {
      let obj = {};
      if (Object.prototype.toString.call(filter[key]) === '[object Array]') {
        obj[key] = filter[key];
      } else {
        obj[key] = [{ '=': filter[key] }];
      }
      return obj;
    });
}
/**
 * @param {Object} config = { hasRetErrorTip: true } fetch方法配置
 * 例: {
 *      hasRetErrorTip: true // 是否做错误提示 (success 为 true 时的提示，默认true)
 *      disposalErrorHandle: false // 是否做错误处理(success 为 false 时的处理)
 * }
 * */
export function fetch(options, config = { hasRetErrorTip: true }) {
  let baseURL = window.SITE_CONFIG.baseUrl;
  // if (questionList.indexOf(options.url) != -1) {
  //     baseURL = window.SITE_CONFIG.baseQuestionUrl
  // }
  // let loadingInstance = Loading.service({ fullscreen: true })
  return new Promise((resolve, reject) => {
    switch (options.method) {
      case 'GET':
        options.url += '?';
        options.url += Common.objToParams(options.data);
        options.url =
          (process.env.NODE_ENV !== 'production' &&
          process.env.NODE_ENV !== 'testing' &&
          process.env.OPEN_PROXY
            ? '/proxyApi/'
            : baseURL) + options.url;
        break;
      case 'DELETE':
        options.url += '?';
        options.url += Common.objToParams(options.data);
        options.url =
          (process.env.NODE_ENV !== 'production' &&
          process.env.NODE_ENV !== 'testing' &&
          process.env.OPEN_PROXY
            ? '/proxyApi/'
            : baseURL) + options.url;
        break;
      case 'POST':
        Object.keys(options.data).forEach((key) => {
          if (
            !options.data[key] &&
            options.data[key] !== 0 &&
            options.data[key] !== null &&
            options.data[key] === '0'
          ) {
            delete options.data[key];
          }
        });
        if (
          options.data.condition &&
          Object.prototype.toString.call(options.data.condition) ===
            '[object Object]'
        ) {
          options.data.condition = parseFilter(options.data.condition);
        }

        options.data =
          options.restype == 'form'
            ? options.data
            : JSON.stringify(options.data);
        options.url =
          (process.env.NODE_ENV !== 'production' &&
          process.env.NODE_ENV !== 'testing' &&
          process.env.OPEN_PROXY
            ? '/proxyApi/'
            : baseURL) + options.url;
        break;
      case 'PUT':
        options.data = JSON.stringify(options.data);
        options.url =
          (process.env.NODE_ENV !== 'production' &&
          process.env.NODE_ENV !== 'testing' &&
          process.env.OPEN_PROXY
            ? '/proxyApi/'
            : baseURL) + options.url;
        break;
    }
    let headers = {
      'otter-token': Vue.cookie.get('token'),
      'Content-Type':
        options.restype == 'form'
          ? 'application/x-www-form-urlencoded'
          : 'application/json;charset=UTF-8',
    };
    const http = axios.create({
      baseURL: options.url,
      timeout: 200000,
      headers: headers,
    });

    http(options)
      .then(
        (response) => {
          if (response.status === 200) {
            // loadingInstance.close()
            if (response.data.code == 0 || response.data.code == 200) {
              resolve([null, response.data]);
            } else {
              const { data = {}, status, config = {} } = response;
              if (config.responseType === 'blob') {
                resolve({ data, header: response.headers, status: status });
              } else {
                resolve([true, response.data]);
                message({
                  dangerouslyUseHTMLString: true,
                  message: response.data.msg || response.data.message,
                });
              }
            }
          } else {
            // loadingInstance.close()
            if (response && response.error) {
              const error = response.error;
              resolve([error, null]);
              message({
                dangerouslyUseHTMLString: true,
                message: '请求出错',
              });
            } else {
              //   Toast('网络请求错误')
            }
          }

          handleErrorCode(response.data, config);
        },
        (err) => {
          console.log(err);
          handleErrorCode(error);
          resolve([err, null]);
        }
      )
      .catch((error) => {
        // 请求失败，没有连接到服务器，请求超时或网络错误
        console.trace(error);
        //   Toast('网络似乎卡了一下！')
      });
  });
}

/**
 * oss上传文件
 * @param {String} url
 * @param {Obejct} options
 * @param {Object} config
 */
export function oss(options) {
  let loadingInstance = Loading.service({
    fullscreen: true,
    customClass: 'osscustomClass',
  });
  return new Promise((resolve, reject) => {
    let url = '';
    if (options.host) {
      url = options.host + options.baseUrl;
    } else {
      url =
        (process.env.NODE_ENV !== 'production' &&
        process.env.NODE_ENV !== 'testing' &&
        process.env.OPEN_PROXY
          ? '/proxyApi/'
          : window.SITE_CONFIG.baseUrl) + options.baseUrl;
    }
    const http = axios.create({
      onUploadProgress: (progressEvent) => {
        let percent = ((progressEvent.loaded / progressEvent.total) * 100) | 0;
        loadingInstance.text = percent + '%';
        if (percent == 100) {
          loadingInstance.text = '正在解压';
        }
        // let percent = (progressEvent.loaded / progressEvent.total * 100) | 0
        // 调用onProgress方法来显示进度条，需要传递个对象 percent为进度值
        // 判断数组里是不是当前上传的文件如果是就把进度条数据放进去 并更新视图
        console.log(percent, 'progressEventprogressEventprogressEvent');
      },
      baseURL: url,
      timeout: 20000000,
      headers: {
        'Content-Type': 'multipart/form-data',
        'otter-token': Vue.cookie.get('token'),
        'file-type': options.type,
      },
    });
    http(options)
      .then((response) => {
        loadingInstance.close();
        if (response.status === 200) {
          // 请求返回成功
          if (response.data.code !== 0) {
            message({
              dangerouslyUseHTMLString: true,
              message: response.data.msg || response.data.message,
            });
          } else {
            resolve([null, response.data]);
          }
        } else {
          // 请求返回失败
          if (response && response.error) {
            const error = response.error;
            resolve([error, null]);
            message({
              dangerouslyUseHTMLString: true,
              message: '请求出错',
            });
          } else {
            //   Toast('网络请求错误')
          }
        }
      })
      .catch((error) => {
        // 请求失败，没有连接到服务器，请求超时或网络错误
        console.trace(error);
      });
  });
}
